#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QKeyEvent>
#include <QScreen>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);
}

MainWindow::~MainWindow() { delete ui; }

void MainWindow::on_pushButtonHideFullScreen_clicked() {
    if (this->isFullScreen()) {
        this->showNormal();
        ui->widgetControl->show();
        ui->statusbar->show();
    } else {
        this->showFullScreen();
        ui->widgetControl->hide();
        ui->statusbar->hide();
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event) {
    if (this->isFullScreen() && event->key() == Qt::Key_Escape) {
        qDebug() << "ESC";
        this->showNormal();
        ui->widgetControl->show();
        ui->statusbar->show();
    }
}

void MainWindow::on_pushButtonChildFullScreen_clicked() {
    if (!fsWidget_) {
        qDebug() << "enable full screen";

        //        auto scs = QGuiApplication::screens();
        //        for(auto &s: scs) {
        //            qDebug() <<s->geometry();
        //        }

        //        auto ps = this->screen();
        //        qDebug() << "this screen" <<ps->geometry();
        enableChildFullScreen();

    } else {
        qDebug() << "disable full screen";
        //        ui->centralwidget->setWindowFlags(Qt::Window|Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint);
        //        ui->centralwidget->setFocus();
        //        ui->centralwidget->showFullScreen();
        //        fsWidget_->setParent(fsParent_);
        disableChildFullScreen();
    }
}

void MainWindow::enableChildFullScreen() {
//    auto scs = QGuiApplication::screens();
//    for (auto &s : scs) {
//        qDebug() << s->geometry();
//    }

//    auto ps = this->screen();
//    qDebug() << "this screen" << ps->geometry();

    fsWidget_ = ui->openGLWidget;
    fsFlags_ = fsWidget_->windowFlags();

    fsWidget_->setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint |
                              Qt::FramelessWindowHint);
    fsWidget_->setFocus();
    fsWidget_->showFullScreen();
    fsWidget_->installEventFilter(this);
}

void MainWindow::disableChildFullScreen() {
    fsWidget_->setWindowFlags(fsFlags_);
    fsWidget_->showNormal();
    fsWidget_->removeEventFilter(this);

    fsWidget_ = nullptr;
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event) {
    if (fsWidget_ != nullptr && watched == fsWidget_ &&
        event->type() == QEvent::KeyPress) {
        qDebug() << "ESC";
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->key() == Qt::Key_Escape) {
            disableChildFullScreen();

            return true; // 事件已处理，不传递给其他对象
        }
    }

    return QMainWindow::eventFilter(watched, event); // 将事件传递给基类处理
}
